# -*- coding: utf-8 -*-

import urllib
import urllib2
# import pycurl
import StringIO
import json
import logging
import threading
import hashlib
import time
import weixin_config
import datetime
import os
import ConfigParser

_loggle = logging.getLogger(__name__)


class WeiXinApi(object):
    _instance_lock = threading.Lock()

    def init(self):
        print 'WeiXinApi __init__'
        # config = ConfigParser.ConfigParser()
        # env_dist = os.environ
        # config_file = env_dist["MX_CONFIG"]
        # # config_file = "/odoo/apps/igreen/mx_config.conf"
        # config.read(config_file)

        self._appId = "wx53f53fda3c2e5a64"
        self._secret = "b328b2e979af46c9713f4023d310f185"
        self._accessToken = ""
        self._expires_in = 0
        self._get_time = datetime.datetime.now()

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            orig = super(WeiXinApi, cls)
            cls._instance = orig.__new__(cls, *args, **kwargs)
            cls._instance.init()
        return cls._instance

    def auth(self, code):
        url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s" \
              "&grant_type=authorization_code" % (self._appId, self._secret, code)

        header_dict = {"Content-Type": "application/json"}
        _loggle.info(url)

        param_json = "{}"
        request = urllib2.Request(url=url, data=param_json, headers=header_dict)
        response = urllib2.urlopen(request)
        response_str = response.read()
        response_dict = json.loads(response_str)
        return response_dict

    def get_access_token(self):
        diff = (datetime.datetime.now() - self._get_time).seconds
        if self._accessToken == "" and (diff - self._expires_in + 600) > 0:
            url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' \
                  % (self._appId, self._secret)
            request = urllib2.Request(url)
            response = urllib2.urlopen(request)
            response_str = response.read()

            response_dict = json.loads(response_str)
            error_code_key = "errcode"
            access_token_key = "access_token"
            expires_in_key = "expires_in"
            error_code_message = "errmsg"
            if response_dict.has_key(access_token_key):
                self._accessToken = response_dict[access_token_key]
                self._expires_in = response_dict[expires_in_key]
            else:
                raise Exception(response_dict[error_code_message])

        return self._accessToken

    def sendTemplateMessage(self, openid, template_id, form_id, page, message, emphasis_keyword):
        try:
            _loggle.info("notice -----" + json.dumps(message))

            accessToken = self.get_access_token()
            url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s" \
                  % (accessToken)
            head = {'Content-Type': 'application/json'}
            messageBody = {
                "touser": openid,
                "template_id": template_id,
                "page": page,
                "form_id": form_id,
                "data": message,
                "emphasis_keyword": emphasis_keyword
            }

            # data=urllib.urlencode(messageBody)
            data = json.dumps(messageBody)
            _loggle.info(data)

            # curl = pycurl.Curl()
            # buf = StringIO.StringIO()
            # curl.setopt(pycurl.WRITEFUNCTION, buf.write)
            # curl.setopt(pycurl.SSL_VERIFYPEER, 0)
            # curl.setopt(pycurl.SSL_VERIFYHOST, 0)
            # curl.setopt(pycurl.POSTFIELDS, data)
            # curl.setopt(pycurl.URL, url)
            # curl.setopt(pycurl.HTTPHEADER, head)
            # curl.perform()
            # result = buf.getvalue()
            # buf.close()

            result = urllib2.Request(url, data, head)
            f = urllib2.urlopen(result)
            response = f.read()
            f.close()

            result_dict = json.loads(response)

            if result_dict["err_code"] != "0":
                raise Exception(result_dict["err_msg"])

            return {"err_code": 0, "err_msg": ""}
        except Exception as ex:
            _loggle.info("111-------")
            _loggle.info(ex.message)
            return {"err_code": 0, "err_msg": ex.message}


WeiXinApiObj = WeiXinApi()
